package com.zhaoc.realm;

import com.zhaoc.domain.system.Permission;
import com.zhaoc.domain.system.Role;
import com.zhaoc.domain.system.User;
import com.zhaoc.service.IPermissionService;
import com.zhaoc.service.IRoleService;
import com.zhaoc.service.IUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * <p>title:com.zhaoc.realm</p>
 * date:2018/8/21 0021
 * time:10:32
 * author:赵成
 * user:13566
 */
//自定义Realm,实现安全数据连接
//@Service("bosRealm")
public class RosRealm extends AuthorizingRealm {

    @Autowired
    private IUserService userService;

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IPermissionService permissionService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("进入shiro的授权管理");
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        //根据当前登陆用户查询对应角色和权限
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        //调用业务层查询角色
        List<Role> roles = roleService.findByUser(user);
        for (Role role:roles) {
            authorizationInfo.addRole(role.getKeyword());
        }
        //然后调用业务层查询权限
        List<Permission> permissions = permissionService.findByUser(user);
        for (Permission permission : permissions) {
            authorizationInfo.addStringPermission(permission.getKeyword());
        }
        return authorizationInfo;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
       //进入了授权认证
        System.out.println("进入了shiro的认证管理");
        //转换token
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;

        //根据用户名查询用户信息
        User user = userService.findByUsername(usernamePasswordToken.getUsername());

        if (user == null){
            //用户不存在
            return null;
        }else {
            //用户名存在
            /**
             * 参数一:期望登陆后,保存在Subject中信息
             * 参数二:如果返回null,说明用户不存在,报用户名
             * 参数三:realm名称
             * 当返回用户密码时,securityManager安全管理器,自动比较返回密码和用户输入密码是否一致
             * 如果一致,则登陆成功,如果密码不一致,报密码错误异常
             */
            return new SimpleAuthenticationInfo(user,user.getPassword(),getName());
        }
    }
}
